package service.validation;

import org.springframework.validation.Errors;
import entities.Status;
import service.configuration.FieldType;
import service.configuration.IFieldConfig;

public class FieldValidator {
	
	public static final Status statusError = Status.SoftError;
	public static final Status statusValid = Status.Valid;
	
	public boolean isEmpty(String value, IFieldConfig conf) {
		return value == null 
		    || value.isEmpty() 
			|| value.matches("\\s*")
		    || (conf.getType() == FieldType.text 
			    && value.matches("(\\s)*(<[^>]*>(\\s)*)*"));
	}
	
	private boolean isNotFilled(String value, IFieldConfig conf) {
		return ! conf.isOptional() && isEmpty(value, conf);
	}
	
	public Status validate(String value, IFieldConfig conf) {
		
		if (isNotFilled(value, conf)) {
			return statusError;
		}
		
		return statusValid;
	}
	
	public Status validate(String name, String value, IFieldConfig conf, Errors errors) {
		
		if (isNotFilled(value, conf)) {
			errors.rejectValue(name, "error.field.required");
			return statusError;
		}

		return statusValid;
	}
}
